package com.hwtx.soa.registry.impl;

import com.hwtx.soa.registry.ZkClient;
import com.hwtx.soa.registry.path.Path;
import com.hzgj.bcl.soa.registry.RegistryUpdater;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by warning5 on 17-2-17.
 */
public class ZkRegistryUpdater implements RegistryUpdater {

    protected static final Logger logger = LoggerFactory.getLogger(ZkRegistryUpdater.class);
    protected ZkClient client;
    private Path path;

    public ZkRegistryUpdater(ZkClient client, Path path) {
        this.client = client;
        this.path = path;
    }

    @Override
    public RegistryUpdater.Result downService(String service, String ipAndPort) {

        String child = path.getProviderChildByServiceAndIpPort(client, service, ipAndPort);

        if (child == null) {
            return new Result(false, "service " + service + " not exist,can't down it.");
        }
        Result result;

        String downPath = path.getDownPath(service, child);
        String upPath = path.getUpPath(service, child);
        try {
            client.create(downPath, true);
            if (client.delete(upPath)) {
                result = getResult(true, "down service " + service + " of " + ipAndPort + " success.");
            } else {
                client.delete(downPath);
                result = getResult(false, "delete up service " + service + " of " + ipAndPort + " failure,up it again.");

            }
        } catch (Exception e) {
            Throwable t = e;
            logger.error("Failed to down " + child + " cause: " + t.getMessage(), t);
            result = getResult(false, "down service " + service + " of " + ipAndPort + " failure. ");
        }

        return result;
    }


    @Override
    public Result upService(String service, String ipAndPort) {

        String child = path.getDownChildByServiceAndIpPort(client, service, ipAndPort);
        if (child == null) {
            return new Result(false, "service " + service + " not exist,can't up it.");
        }
        Result result;

        String downPath = path.getDownPath(service, child);
        String upPath = path.getUpPath(service, child);
        try {
            client.create(upPath, true);
            if (client.delete(downPath)) {
                result = getResult(true, "up service " + service + " of " + ipAndPort + " success.");
            } else {
                client.delete(upPath);
                result = getResult(false, "delete down service " + service + " of " + ipAndPort + " failure,down it again.");

            }
        } catch (Exception e) {
            Throwable t = e;
            logger.error("Failed to up " + child + " cause: " + t.getMessage(), t);
            result = getResult(false, "up service " + service + " of " + ipAndPort + " failure. ");
        }

        return result;
    }

    private Result getResult(boolean success, String message) {
        return new Result(success, message);
    }
}
